#include "scanner.h"
#include <QDir>
#include <QFileInfo>
#include <QThread>
#include <QFile>
#include <QTextStream>

Scanner::Scanner(QObject *parent) : QObject(parent)
{
}

Scanner::~Scanner()
{
    stopScan();
    if (m_thread) {
        m_thread->wait();
        delete m_thread;
    }
}

void Scanner::startScan(const QString &folderPath)
{
    stopScan(); // 停止之前的扫描
    m_stopFlag.storeRelaxed(0);
    m_results.clear();

    m_thread = QThread::create([this, folderPath]() {
        scanDirectory(folderPath);
        if (!m_stopFlag.loadRelaxed()) {
            emit scanFinished();
        }
    });

    connect(m_thread, &QThread::finished, m_thread, &QObject::deleteLater);
    m_thread->start();
}

void Scanner::stopScan()
{
    m_stopFlag.storeRelaxed(1);
    if (m_thread && m_thread->isRunning()) {
        m_thread->wait();
    }
}

void Scanner::scanDirectory(const QString &path)
{
    QDir dir(path);
    const auto entries = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);

    for (const QFileInfo &info : entries) {
        if (m_stopFlag.loadRelaxed()) {
            emit scanStopped();
            return;
        }

        if (info.isDir()) {
            scanDirectory(info.absoluteFilePath());
        } else {
            const QString absPath = info.absoluteFilePath();
            const qint64 size = info.size();
            m_results.append({absPath, size});
            emit fileScanned(absPath, size);
        }
    }
}

bool Scanner::saveResult(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QTextStream out(&file);
    for (const auto &[path, size] : m_results) {
        out << path << "," << size << "\n";
    }

    file.close();
    return true;
}
